const db = require("../model/mysql/db");
const util = require("../common/util");
const moment = require('moment-timezone');

async function addReview(req, res) {
    const requiredFields = ['user_id','post_id','review'];
    const missing = requiredFields.filter(field => !req.body[field]);
    if (missing.length > 0) {
        return res.status(400).json(util.FormatJSONData(400, `缺少必填字段: ${missing.join(', ')}`));
    }

    const date = new Date();
    const chinaTime = new Date(date.getTime() + 8 * 60 * 60 * 1000);
    console.log(chinaTime.toISOString());

    let params = [
            req.body.user_id,
            req.body.post_id,
            req.body.review,
            chinaTime.toISOString()
        ];
    
    try {
        util.log(req.body);
        let sql = "INSERT INTO reviews (user_id,post_id,review,review_time) VALUES(?,?,?,?);"
        let result =await db.query(sql,params);
        
        if (result.affectedRows == 1){
            console.log(util.FormatJSONData(201,"插入成功",result));
            sql = "Update posts set review_count = review_count + 1 where post_id = ?;"
            result =await db.query(sql,[req.body.post_id]);
            util.log("更新成功");
            res.status(201).json(util.FormatJSONData(201,"更新成功"));
        }
        
    } catch{
        util.err(500,"错误！！！");
        res.status(500).json(util.FormatJSONData(500,"服务器错误"));
    };
}

async function findReview(req, res) {
    try {
        let sql = `SELECT 
            r.reviewid,
            r.post_id,
            r.user_id,
            r.review,
            r.review_time,
            us.avatar,
            us.nickname
            FROM reviews as r
            LEFT JOIN users AS us ON r.user_id = us.user_id
            WHERE post_id = ?
            ORDER BY r.reviewid DESC;`
        let result =await db.query(sql,[req.params.post_id]);
        util.log(result);
        res.status(200).json(util.FormatJSONData(200,"查询成功",result));
    } catch{
        util.err(500,"错误！！！");
        res.status(500).json(util.FormatJSONData(500,"服务器错误"));
    }
}

async function findMe(req, res){
    util.log(req.params);
    let uid = parseInt(req.params.user_id);
    try {
        let sql = `SELECT 
            r.reviewid,
            r.post_id,
            r.user_id,
            r.review,
            r.review_time,
            us.avatar,
            us.nickname
            FROM reviews as r
            LEFT JOIN users AS us ON r.user_id = us.user_id
            WHERE us.user_id = ?
            ORDER BY r.reviewid DESC;`
        util.log("FJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ")
        let result =await db.query(sql,[uid]);
        util.log(result);
        res.status(200).json(util.FormatJSONData(200,"查询成功",result));
    } catch{
        util.err(500,"错误！！！");
        res.status(500).json(util.FormatJSONData(500,"服务器错误"));
    }
}

module.exports = {
    addReview,
    findReview,
    findMe
}